const router = require('koa-router')()
const svgCaptcha = require("svg-captcha")
const user = require('./user.json')
const jwt = require('jsonwebtoken');
const formidable = require("formidable")
const path = require("path")
const mime = require("mime-types")
const fs = require("fs");
const { Console } = require('console');
var verCode = ''


router
// 登录
router.post('/', async (ctx, next) => {
  const secretkey = 'howdoyoudo'; //密钥
  let sql = "select * from zhanghao where username='" + ctx.request.body.username + "' and pwd='" + ctx.request.body.pwd + "'";
  let result = await ctx.db.EXCUTE(sql);
  console.log(ctx.request.body.username === result[0].username)
  console.log(ctx.request.body.pwd == result[0].pwd)
  if (ctx.request.body.username === result[0].username && ctx.request.body.pwd == result[0].pwd &&
    ctx.request.body.past.toLowerCase() === verCode.toLowerCase()) {
    let token = jwt.sign({ username: ctx.request.body.username }, secretkey);
    console.log("账号正确")
    ctx.body = {
      error_code: 1,
      token: token
    }
  } else {
    console.log("不对")
    ctx.body = { error_code: 0 }
  }
})
// 验证码
router.get('/code', async (ctx) => {
  var captcha = svgCaptcha.create({    //这种生成的是随机数验证码
    size: 4,    //验证码长度
    fontSize: 50,   //字体大小
    width: 100,
    height: 40,
    // background:'#cc8801'
  });
  verCode = captcha.text
  ctx.response.type = 'image/svg+xml';
  ctx.body = captcha.data;
});
// 上传图片
router.post('/upload', async (ctx, next) => {
  const filePath = path.join(__dirname, '../public/upload')
  let form = formidable({
    uploadDir: filePath,
    keepExtensions: true,
    multiples: true
  });
  form.parse(ctx.req, async (err, fields, files) => {
    let type = files.file['mimetype']//类型
    let size = files.file.size//大小
    let src = files.file.originalFilename//地址同名字，获取里拼接得到地址
    let img_name = files.file.originalFilename//名字
    let sql = "insert into photo (img_name,size,type,src) VALUES('" + img_name + "','" + size + "','" + type + "','" + src + "')"
    let result = await ctx.db.EXCUTE(sql);
    console.log(result)
    if (err) {
      console.log(err)
    } else {
      let oldpath = path.join(__dirname, '../public/upload/' + files.file.newFilename)
      let newpath = path.join(__dirname, '../public/upload/' + files.file.originalFilename)
      fs.rename(oldpath, newpath, (err) => {
        if (err) {
          console.log('failed')
        } else {
          console.log('success')
        }
      })
    }
  })
  ctx.body = '123'
})
// 获取图片
router.get("/getlist", async (ctx, next) => {
  let sql = "select * from photo";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  let list = []
  result.forEach(item=>{
    let imgPath = path.join(__dirname, "../public/upload/" + item.src) //地址
    list.push({
      type:item.type,
      size:item.size + 'b',
      name:item.img_name,
      src:fs.readFileSync(imgPath, "base64")
    })
  })
  ctx.body = list
})
// 删除图片
router.post("/dellist", async (ctx, next) => {
  let img_name = ctx.request.body.name;
  let sql = "delete from photo where img_name = '"+img_name+"'"
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "删除失败"
  }
});

//About.vue

// 编辑
router.post("/subeditform", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let userName = ctx.request.body.userName;
  let telephoneNum = ctx.request.body.telephoneNum;
  let eMail = ctx.request.body.eMail;
  let site = ctx.request.body.site;
  let timer = ctx.request.body.timer;
  // let sql = "update user set userName="
  var sql = "update user1 set userName='" + userName + "',tel='" + telephoneNum + "',eMail='" + eMail + "',site='" + site + "',timer='" + timer + "' where chapterId=" + chapterId + "";
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = '编辑失败'
  }
})
// 添加数据
router.post("/subform", async (ctx, next) => {
  let userName = ctx.request.body.userName;
  let tel = ctx.request.body.telephoneNum;
  let eMail = ctx.request.body.eMail;
  let site = ctx.request.body.site;
  let timer = ctx.request.body.timer;
  let dateObj = new Date(timer);
  timer = dateObj.getFullYear() + "-"
    + (dateObj.getMonth() + 1) + "-"
    + dateObj.getDate();
  let sql = "insert into user1 (userName,tel,eMail,site,timer) VALUES('" + userName + "','" + tel + "','" + eMail + "','" + site + "','" + timer + "')"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  if (result) {
    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "添加失败"
  }
})
// 删除
router.post("/delchapter", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let sql = "delete from user1 where chapterId=" + chapterId
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "删除失败"
  }
})
// 获取
router.get("/getnum", async (ctx, next) => {
  let num = []
  let sql = "select * from user1";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    num.push({
      userName: item.userName,
      telephoneNum: item.tel,
      eMail: item.eMail,
      site: item.site,
      timer: item.timer,
      chapterId: item.chapterId
    })
  })
  ctx.body = num;
})
// 置顶
router.post("/movetotop",async(ctx,next)=>{
  let chapterId = ctx.request.body.chapterId
  console.log(ctx.request.body.chapterId)
  let sql = "select *  from logistics order by chapterId='" + chapterId +"'DESC" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body=result
})
// 查询
router.post("/select",async(ctx,next)=>{
  let text = ctx.request.body.text
  let sql = "select *  from user1 where userName Like '%" + text + "%'" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})




// Logistics.vue
// 修改
router.post("/xiugai", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let userName = ctx.request.body.userName;
  let road = ctx.request.body.road;
  let site = ctx.request.body.site;
  let tel = ctx.request.body.tel;
  let timer = ctx.request.body.timer;
  var sql = "update logistics set userName='" + userName + "',road='" + road + "',site='" + site + "',tel='" + tel + "',timer='" + timer + "' where chapterId=" + chapterId + "";
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = "修改失败"
  }
})
// 添加
router.post("/sublog", async (ctx, next) => {
  let userName = ctx.request.body.userName;
  let road = ctx.request.body.road;
  let site = ctx.request.body.site;
  let tel = ctx.request.body.tel;
  let timer = ctx.request.body.timer;
  let dateObj = new Date(timer);
  timer = dateObj.getFullYear() + "-"
    + (dateObj.getMonth() + 1) + "-"
    + dateObj.getDate();
  console.log(tel)
  let sql = "insert into logistics (userName,road,site,tel,timer) VALUES('" + userName + "','" + road + "','" + site + "','" + tel + "','" + timer + "')"
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = "修改失败"
  }
})
// 删除
router.post("/dellog", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let sql = "delete from logistics where chapterId=" + chapterId
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "删除失败"
  }
})
// 获取
router.get("/getlognum", async (ctx, next) => {
  let logNum = []
  let sql = "select * from logistics ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      userName: item.userName,
      tel: item.tel,
      road: item.road,
      site: item.site,
      timer: item.timer,
      chapterId: item.chapterId
    })
  })
  ctx.body = logNum;
})
// 查询
router.post("/selectlog",async(ctx,next)=>{
  let text = ctx.request.body.text
  let sql = "select *  from logistics where userName Like '%" + text + "%'" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})
module.exports = router

// 置顶
router.post("/movetotop",async(ctx,next)=>{
  let chapterId = ctx.request.body.chapterId
  console.log(ctx.request.body.chapterId)
  let sql = "select *  from logistics1 order by chapterId='" + chapterId +"'DESC" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body=result
})
// 查询
router.post("/select",async(ctx,next)=>{
  let text = ctx.request.body.text
  let sql = "select *  from user where userName Like '%" + text + "%'" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})















// logistics1.vue
// 修改
router.post("/xiugai", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let userName = ctx.request.body.userName;
  let road = ctx.request.body.road;
  let site = ctx.request.body.site;
  let tel = ctx.request.body.tel;
  let timer = ctx.request.body.timer;
  var sql = "update logistics1 set userName='" + userName + "',road='" + road + "',site='" + site + "',tel='" + tel + "',timer='" + timer + "' where chapterId=" + chapterId + "";
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = "修改失败"
  }
})
// 添加
router.post("/sublog", async (ctx, next) => {
  let userName = ctx.request.body.userName;
  let road = ctx.request.body.road;
  let site = ctx.request.body.site;
  let tel = ctx.request.body.tel;
  let timer = ctx.request.body.timer;
  let dateObj = new Date(timer);
  timer = dateObj.getFullYear() + "-"
    + (dateObj.getMonth() + 1) + "-"
    + dateObj.getDate();
  console.log(tel)
  let sql = "insert into logistics1 (userName,road,site,tel,timer) VALUES('" + userName + "','" + road + "','" + site + "','" + tel + "','" + timer + "')"
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = "修改失败"
  }
})
// 删除
router.post("/dellog", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let sql = "delete from logistics1 where chapterId=" + chapterId
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "删除失败"
  }
})
// 获取
router.get("/getlognum", async (ctx, next) => {
  let logNum = []
  let sql = "select * from logistics1 ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      userName: item.userName,
      tel: item.tel,
      road: item.road,
      site: item.site,
      timer: item.timer,
      chapterId: item.chapterId
    })
  })
  ctx.body = logNum;
})

router.post("/selectlog",async(ctx,next)=>{

  // console.log(1)
  // console.log(ctx.request.body)
  // ctx.body="1"
  let text = ctx.request.body.text
  let sql = "select *  from logistics1 where userName Like '%" + text + "%'" 
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})




//文本框提交
router.post("/selectlogs",async(ctx,next)=>{
  console.log(ctx.request.body)
 
  ctx.body="1"
})
module.exports = router





